#include <iostream>
#include <string>
#include <unistd.h>

#define DEBUG 1 

bool getCgiQueryString(std::string& query_string)
{
    bool result = false ; 
    std::string query_method = getenv("METHOD") ;

#ifdef DEBUG
    std::cerr << query_method << std::endl; 
    if(query_method == "")
    {
        std::cerr << "get env error" << std::endl ;
    }
#endif 

    if(query_method == "POST")
    {
        int content_length = atoi(getenv("CONTENT_LENGTH"));
        char tem  =  0 ; 
        while(content_length)
        {
            read(0, &tem, 1);
            query_string.push_back(tem); 
            content_length-- ; 
        }
        result = true ; 

    }
    else if (query_method == "GET")
    {
        query_string =  getenv("QUERY_STRING");
        result = true ; 
    }
    else
    {
        result = false ;
    }

    return result ;
}


    bool cutString(const std::string &target, std::string& out1, std::string& out2, std::string sep)
    {
#ifdef DEBUG
    std::cerr << "debug :" << target << std::endl ; 
    if(target == "")
    {
        std::cerr << "cutString env error"  << std::endl;
    }
#endif 


        int pos = target.find(sep);
        if(pos != std::string::npos)
        {
            out1 = target.substr(0, pos);
            out2 = target.substr(pos + sep.size()) ;
            return true ;
        }
        return false ; 
    }